#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <math.h>

int run(int n) {
    int res = 0;
    while (n > 0) {
        res += pow(n % 10, 2);
        n /= 10;
    }
    printf("run, res = %d\n", res);
    return res;
}

bool isHappy(int n) {
    if (n == 1) return true;
    int res = n;
    int rounds[50] = { 0 };
    int count = 0;
    while(true) {
        res = run(res);
        if (res == 1) {
            return true;
        }
        for (int i = 0; i < count; i++) {
            if (res == rounds[i]) return false;
        }
        rounds[count] = res;
        count++;
    }
    return false;
}

int main() {
    int num = 87236;
    bool res = isHappy(num);
    printf("res = %d\n", res);
    return 0;
}